package com.yune.activity.history;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.yune.activity.App;
import com.yune.adapter.HistoryListAdapter;
import com.yune.adapter.PlayListAdapter;
import com.yune.bean.HistoryBean;
import com.yune.databinding.ActivityHistorylistBinding;
import com.yune.databinding.ActivityPlaylistBinding;
import com.yune.utils.Network;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HistoryListViewModel extends AndroidViewModel {
    private HistoryListAdapter adp;
    private final List<HistoryBean> data=new ArrayList<>();
    @SuppressLint("StaticFieldLeak")
    private HistoryListActivity historyListActivity;
    @SuppressLint("StaticFieldLeak")
    public HistoryListViewModel(@NonNull Application application) { super(application); }
    public void setBinding(ActivityHistorylistBinding binding, HistoryListActivity historyListActivity) {
        this.historyListActivity=historyListActivity;
        adp=new HistoryListAdapter(historyListActivity,data);
        binding.setAdp(adp);
        binding.historylistList.setOnItemClickListener((parent, view, position, id) -> Network.get("https://api2.bmob.cn/1/classes/song/" + data.get(position).songOid, res -> {
            JSONObject result = new JSONObject(res);
            Intent intent = new Intent();
            intent.setAction("serviceReceiver");
            intent.putExtra("cmd","newPlay");
            intent.putExtra("songName",result.getString("songName"));
            intent.putExtra("singer",result.getString("singer"));
            intent.putExtra("picture",result.getString("picture"));
            intent.putExtra("songId",result.getString("songId"));
            intent.putExtra("fromWeb",true);
            intent.putExtra("ifAddedOid",result.getString("objectId"));
            Network.callApi("https://autumnfish.cn/song/url?id=" + result.getString("songId"), new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {}
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    try {
                        assert response.body() != null;
                        JSONObject obj=new JSONObject(response.body().string()).getJSONArray("data").getJSONObject(0);
                        intent.putExtra("songUrl",obj.getString("url"));
                        historyListActivity.sendBroadcast(intent);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }));
        binding.historylistList.setOnItemLongClickListener((parent, view, position, id) -> {
            AlertDialog.Builder dia=new AlertDialog.Builder(historyListActivity);
            dia.setTitle("提示").setMessage("确认删除吗？").setPositiveButton("删除", (dialog, which) -> {
                try {
                    JSONObject loginMsg=new JSONObject(App.sp.getString("loginMsg",""));
                    String url="https://api2.bmob.cn/1/classes/history?where=" + URLEncoder.encode("{\"userObjectId\":\""+loginMsg.getString("objectId")+"\",\"songObjectId\":\""+data.get(position)+"\"}");
                    Network.get(url,res1->{
                        String songIdInList=new JSONObject(res1).getJSONArray("results").getJSONObject(0).getString("objectId");
                        Network.delete("https://api2.bmob.cn/1/classes/history/" + songIdInList, res -> historyListActivity.runOnUiThread(this::refresh));
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }).setNeutralButton("取消",null).show();
            return true;
        });
        refresh();
    }
    private void refresh() {
        try {
            JSONObject loginMsg = new JSONObject(App.sp.getString("loginMsg", ""));
            String userObjectId=loginMsg.getString("objectId");
            Network.get("https://api2.bmob.cn/1/classes/history?order=-createdAt&where=" + URLEncoder.encode("{\"userObjectId\":\""+userObjectId+"\"}"), res -> {
                historyListActivity.runOnUiThread(() -> {
                    data.clear();
                    try {
                        JSONArray result = new JSONObject(res).getJSONArray("results");
                        for (int i = 0; i < result.length(); i++) {
                            data.add(new HistoryBean(result.getJSONObject(i).getString("songObjectId"),userObjectId));
                        }
                        adp.notifyDataSetChanged();
                    } catch (JSONException e) {
                        adp.notifyDataSetChanged();
                    }
                });
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
